<template>
  <vxe-column v-bind="$attrs">
    <template v-slot="scope">
      <el-form-item v-if="isEdit(scope.row)" label="" :prop="$attrs.field">
        <el-date-picker
          ref="inputWidget"
          style="width: 100%"
          :type="handlerType"
          start-placeholder=""
          end-placeholder=""
          :clearable="true"
          :size="size"
          :format="handlerFormat"
          :disabled="disabled"
          :value-format="valueFormat"
          :model-value="getRowDataValue"
          @update:modelValue="onChange"
        />
      </el-form-item>
      <!-- 判断是否有default的slot -->
      <slot v-else-if="$slots.default" :row="scope.row" />
      <!-- 默认显示内容 -->
      <span v-else>{{ getRowDateLabel(scope.row) }}</span>
    </template>
  </vxe-column>
</template>

<script setup lang="ts">
import { VxeColumn } from 'vxe-table';
import useTableInlineColumn from './useTableInlineColumn';
import { ANY_OBJECT } from '@/types/generic';
import { formatDate } from '@/common/utils';

const emit = defineEmits(['change']);
type InlineDateColumnProps = {
  size: string;
  type: string;
  format: string;
  valueFormat: string;
  clearable: boolean;
  disabled: boolean;
  // Jie. 20250626 传入列值用于计算
  column?: ANY_OBJECT;
};
const props = withDefaults(defineProps<InlineDateColumnProps>(), {
  size: 'default',
  type: 'date',
  format: 'YYYY-MM-DD HH:mm:ss',
  valueFormat: 'YYYY-MM-DD HH:mm:ss',
  clearable: true,
  disabled: false,
});
const inputWidget = ref();
const { isEdit, getRowData, getRowValue, onChange, reset } = useTableInlineColumn(
  false,
  emit,
  inputWidget,
);

// Jie. 20250626 计算日期类型
const handlerType = computed(() => {
  if (props.column) {
    if (props.column.dateType === 'YYYY') {
      return 'year';
    } else if (props.column.dateType === 'YYYY-MM') {
      return 'month';
    } else if (props.column.dateType === 'YYYY-MM-DD HH:mm:ss') {
      return 'datetime';
    } else {
      return props.type;
    }
  } else {
    return props.type;
  }
});

// Jie. 20250626 获取格式化字符串
const handlerFormat = computed(() => {
  if (props.column) {
    return props.column.dateType;
  } else {
    return props.format;
  }
});

// Jie. 20250626 获取日期时间展示内容
const getRowDateLabel = row => {
  if (props.column) {
    return getRowValue(row) ? formatDate(getRowValue(row), props.column.dateType) : undefined;
  } else {
    return getRowValue(row);
  }
};

// Jie. 20250626 获取日期时间值
const getRowDataValue = computed(() => {
  if (props.column) {
    return getRowData.value ? formatDate(getRowData.value, props.valueFormat) : undefined;
  } else {
    return getRowData.value;
  }
});

defineExpose({
  reset,
  focus: () => {
    if (inputWidget.value) inputWidget.value.focus();
  },
});
</script>

<style></style>
